package com.bwie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bwie.common.domain.Borrow;
import com.bwie.common.domain.Card;
import com.bwie.common.domain.request.BorrowRequest;
import com.bwie.mapper.BorrowMapper;
import com.bwie.mapper.CardMapper;
import com.bwie.service.BorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private CardMapper cardMapper;


    @Override
    public PageInfo<BorrowRequest> list(BorrowRequest borrow) {
        PageHelper.startPage(borrow.getPageNum(),borrow.getPageSize());
        List<BorrowRequest> list = borrowMapper.list(borrow);
        PageInfo<BorrowRequest> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public void upd(BorrowRequest borrow) {
        String borrowDaily = borrow.getBorrowDaily();
        String bankName = borrow.getBankName();
        String limit = borrow.getBorrowLimit();
        String contRate = borrow.getContRate();
        Integer contPrice = borrow.getContPrice();
        Integer borrowPrice = borrow.getBorrowPrice();
        if(StrUtil.isBlank(borrowDaily)){
            throw new RuntimeException("日供不能为空");
        }
        if (StrUtil.isBlank(bankName)) {
            throw new RuntimeException("银行名称不能为空");
        }
        if(StrUtil.isBlank(limit)){
            throw new RuntimeException("借款额度不能为空");
        }
        if(StrUtil.isBlank(contRate)){
            throw new RuntimeException("月供不能为空");
        }
        //每单出资需要给平台缴纳0.03%的一次性手续费，计算预计收益需扣除
        borrow.setIncomePrice((int) (borrow.getIncomePrice()-borrow.getIncomePrice()*0.003));

        //出资金额填写后需实时计算出资比率，比率计算正确（比率为出资金额/借款金额 * 100%）
//        borrow.setContRate(String.valueOf(Integer.getInteger("%.2f",(contPrice/borrowPrice)*100)));
        //出资金额不可大于借款金额，需要限制（5分）
        if(contPrice==null){
            throw new RuntimeException("不能为空");
        }
        if(contPrice>=borrowPrice){
            throw new RuntimeException("出资金额不可大于借款金额");
        }
        borrowMapper.upd(borrow);
        Card card = new Card();
        card.setBorrowId(borrow.getBorrowId());
        card.setCardPrice(borrow.getBorrowPrice());
        cardMapper.add(card);

    }

    @Override
    public PageInfo<Card> cardList(Card card) {
        PageHelper.startPage(card.getPageNum(),card.getPageSize());
        List<Card> list = cardMapper.list(card);
        PageInfo<Card> info = new PageInfo<>(list);
        return info;
    }

}
